﻿using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using YAKEJI.Abp.Domain.Repositories;
using YAPACS.BusinessObjects.Exams;
using YAPACS.BusinessObjects.Managements.Exams;
using YAPACS.Organizations;
using YAPACS.Workflows;

namespace YAPACS.RisServer.Workflows.Report;

public class SetCriticalValue(IRepository<BusinessObjects.Exams.Report, Guid> reportRepository,
    IRepository<ReportPanicValue, Guid> panicValueRepository,
    IRepository<ApplyDoctor, Guid> applyDoctorRepository,
    ICurrentUserOrganization currentUserOrganization,
    IRepository<ApplicationUser, Guid> userRepository,
    IRepository<Department, Guid> departmentRepository,
    ISendCriticalValue sendCriticalValue) : WorkflowBase, ISetCriticalValue, ITransientDependency
{
    private readonly IRepository<BusinessObjects.Exams.Report, Guid> _reportRepository = reportRepository;
    private readonly IRepository<ReportPanicValue, Guid> _panicValueRepository = panicValueRepository;
    private readonly IRepository<ApplyDoctor, Guid> _applyDoctorRepository = applyDoctorRepository;
    private readonly ICurrentUserOrganization _currentUserOrganization = currentUserOrganization;
    private readonly IRepository<ApplicationUser, Guid> _userRepository = userRepository;
    private readonly IRepository<Department, Guid> _departmentRepository = departmentRepository;
    private readonly ISendCriticalValue _sendCriticalValue = sendCriticalValue;

    protected override async Task<WorkflowOutput> InvokeCoreAsync(WorkflowInput input)
    {
        WorkflowOutput workflowOutput = new WorkflowOutput { Success = false };
        const string key = "Input";
        if (input.ContainsKey(key) && input.GetValueOrDefault(key) is Dictionary<string, object> data)
        {
            ReportPanicValue panicValue = null;
            //新建危急值
            if (data.ContainsKey("panicValueId") && Guid.TryParse(data.GetValueOrDefault("panicValueId")?.ToString(), out Guid panicValueId) && panicValueId != default(Guid))
            {
                panicValue = await _panicValueRepository.GetAsync(panicValueId);
            }
            else
            {
                panicValue = await _panicValueRepository.NewEntityAsync();
                if (data.ContainsKey("reportId"))
                {
                    if (Guid.TryParse(data.GetValueOrDefault("reportId")?.ToString(), out Guid reportId))
                    {
                        var report = await _reportRepository.GetAsync(reportId);
                        panicValue.Report = report;
                    }
                    else
                    {
                        throw new Exception("报告Id转换错误");
                    }
                }
                else
                {
                    throw new Exception("未找到报告");
                }
                //发送者：当前用户
                var user = await _userRepository.GetAsync(_currentUserOrganization.UserId);
                panicValue.SendingDoctor = user;
                panicValue.SendingDepartment = await _departmentRepository.GetAsync(_currentUserOrganization.DepartmentId.Value);
                //接收者：申请医生
                if (data.ContainsKey("applyDoctorId"))
                {
                    if (Guid.TryParse(data.GetValueOrDefault("applyDoctorId")?.ToString(), out Guid applyDoctorId))
                    {
                        var applyDoctor = await _applyDoctorRepository.GetAsync(applyDoctorId);
                        panicValue.ReceivingDoctor = applyDoctor;
                        panicValue.ReceivingDepartment = applyDoctor.Department;
                    }
                }
                panicValue.SendingTime = Clock.Now;
            }
            //发送者电话
            var sendingPhoneNumber = data.GetValueOrDefault("sendingPhoneNumber") as string;
            //接收者电话
            var receivingPhoneNumber = data.GetValueOrDefault("receivingPhoneNumber") as string;
            //危急值结果
            var result = data.GetValueOrDefault("result") as string;
            //备注
            var description = data.GetValueOrDefault("description") as string;
            if (!(panicValue.ReceivingPhoneNumber == receivingPhoneNumber && panicValue.SendingPhoneNumber == sendingPhoneNumber && panicValue.Result == result && panicValue.Description == description))
            {
                panicValue.SendingPhoneNumber = sendingPhoneNumber;
                panicValue.ReceivingPhoneNumber = receivingPhoneNumber;
                panicValue.Result = result;
                panicValue.Description = description;
                panicValue.SendingTimes++;
            }
            workflowOutput = await _sendCriticalValue.InvokeAsync(new WorkflowInput { { "ReportPanicValue", panicValue } });
            if (workflowOutput.Success && (bool)workflowOutput.Data)
            {
                panicValue.LastSendingTime = Clock.Now;
            }
            else
            {
                if (string.IsNullOrWhiteSpace(workflowOutput.Error))
                {
                    workflowOutput.Error = "发送失败";
                }
            }
        }
        return workflowOutput;
    }
}
